package com.bestv.lucene;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 文件搜索器
 * User: Henry
 * Date: 14-5-6
 */
public class FileSearcher {
    private IndexReader indexReader;

    public FileSearcher(String indexDir) throws IOException {
        Directory dir = FSDirectory.open(new File(indexDir));
        indexReader = DirectoryReader.open(dir);
    }

    public void close() throws IOException {
        indexReader.close();
    }

    public ArrayList<Object[]> search(String name, int num) throws ParseException, IOException {
        ArrayList<Object[]> result = new ArrayList<Object[]>();
        IndexSearcher searcher = new IndexSearcher(indexReader);
        Analyzer analyzer = new CJKAnalyzer();
        QueryParser parser = new QueryParser("content", analyzer);
        Query query = parser.parse(name);
        TopDocs hits = searcher.search(query, num);
        for (ScoreDoc scoreDoc : hits.scoreDocs) {
            Document doc = searcher.doc(scoreDoc.doc);
            Object[] row = new Object[2];
            row[0] = doc.get("path");
            row[1] = doc.get("content");
            result.add(row);
        }
        return result;
    }
}
